package com.hxl.dailyworksummary.git;

import com.intellij.openapi.project.Project;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class GitService {
    public List<String> getTodaysCommits(Project project) {
        String projectBasePath = project.getBasePath();
        if (projectBasePath == null) {
            return new ArrayList<>();
        }
        
        File projectDir = new File(projectBasePath);
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        try {
            // 检查是否是Git仓库
            File gitDir = new File(projectDir, ".git");
            if (!gitDir.exists()) {
                List<String> result = new ArrayList<>();
                result.add("当前项目不是Git仓库");
                return result;
            }

            ProcessBuilder processBuilder = new ProcessBuilder(
                    "git", "log",
                    "--since=" + today + " 00:00:00",
                    "--until=" + today + " 23:59:59",
                    "--pretty=format:%s"
            );
            processBuilder.directory(projectDir);

            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            List<String> commits = new ArrayList<>();
            String line;

            while ((line = reader.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    commits.add(line);
                }
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                List<String> result = new ArrayList<>();
                result.add("获取Git提交记录失败");
                return result;
            }

            return commits;
        } catch (Exception e) {
            e.printStackTrace();
            List<String> result = new ArrayList<>();
            result.add("获取Git提交记录时出错: " + e.getMessage());
            return result;
        }
    }
}